//
// GPSMapEdit
// (c) Michael Sotin (m.u.s@mail.ru), 2004
//
// Enhanced metafile EMF map saver.
//

# include "StdAfx.h"
# include "Map.h"
# include "Position.h"
# include "Status.h"
# include "MapView.h"
# include "Save.h"
# include "SaveFileDlg.h"
# include "Globals.h"
# include "Version.h"

class CEmfExport : public CMapSaver {
  public:
	virtual bool CanSave (const map_t & _map) { return true; }
	virtual bool Save (HANDLE _hFile, const char * _strFileName, const map_t & _map) {
		return _Save (_strFileName, "emf", "Enhanced metafile (*.emf)\0*.emf\0", _map);
	}

	bool _Save (const char * _strFileName, const char * _strExt, const char * _strFilter, const map_t & _map);
};

//DECLARE_MAP_EXPORT (CEmfExport, "emf", "emf", "Enhanced metafile");

bool CEmfExport::_Save (const char * _strFileName, const char * _strExt, const char * _strFilter, const map_t & _map)
{
	//
	// Prepare file name.
	//
	char strFileName [MAX_PATH + 1];
	::strncpy (strFileName, _strFileName, MAX_PATH);
	strFileName [MAX_PATH] = '\0';
	if (! SaveFileDlg (_strExt, _strFilter, strFileName))
		return false;

	//
	// Prepare drawing area.
	//
	SetProgressStatus (0);

	rect_t rectVisible;
	RECT rcArea;
	{
		CCritSec::CLock lock (g_cs);

		GetVisibleRect(rectVisible);

		rcArea.left   = XToScreen (rectVisible.x0);
		rcArea.right  = XToScreen (rectVisible.x1);
		rcArea.bottom = YToScreen (rectVisible.y0);
		rcArea.top    = YToScreen (rectVisible.y1);
	}

	//
	// Write the file.
	//
	const char * const szDescription = "Desc\0" MAIN_TITLE " ver " GME_VER_S "\0\0";
	HDC hdcEmf;
	HRGN hClipRgn;

	hdcEmf = ::CreateEnhMetaFile (CClientDC (NULL),
		strFileName, NULL, (LPSTR)szDescription);

	if (! hdcEmf) {
		ErrorMsgBox ("Can't create file:\n %s", strFileName);
		return false;
	}

	::SetViewportOrgEx (hdcEmf, -rcArea.left, -rcArea.top, NULL);
	hClipRgn = ::CreateRectRgn (rcArea.left, rcArea.top,
		rcArea.right, rcArea.bottom);
	if (hClipRgn) {
		::SelectClipRgn (hdcEmf, hClipRgn);
		::DeleteObject (hClipRgn);
	}

	{
		CCritSec::CLock lock (g_cs);

		g_map.Draw (hdcEmf, rectVisible, 0, 100, g_bShowAttachments);
	}
	HENHMETAFILE hEmf;

	hEmf = ::CloseEnhMetaFile (hdcEmf);

	if (! hEmf) {
		ErrorMsgBox ("Error creating file:\n %s", strFileName);
		return false;
	}

	::DeleteEnhMetaFile (hEmf);

	//
	// Complete.
	//
	SetProgressStatus (100);
	Refresh ();

	return true;
}